<?php
apf_require_controller('Oa_Attendance_Abstract');
apf_require_class('Tools_SendMail');
apf_require_class('Tools_Uploader');
apf_require_class('Bll_Attendance_LeaveRecord');
class Oa_Attendance_TripController extends Oa_Attendance_AbstractController {

    private $bll;
    private $post_data = array();
    private $dtp_info;
    private $mail;//邮件实例

    public function handle_request() {
        $this->session_act();
        $this->get_bll();
        $dtp_infos = $this->dtp_info = $this->bll->get_dpt_info();//出差审批人信息
        /*再做一重判断,对特殊人员，需要mike处理的 u.name,u.email,t.department_id*/
        $sp_user_list = array(
                5587=>'michaellv@anjukeinc.com',
                5585=>'garyhu@anjukeinc.com',
                5635=>'julianwang@anjukeinc.com',
                4124=>'justinni@anjukeinc.com',
                5715=>'joychen@anjukeinc.com',
                6872=>'echoyang@anjukeinc.com',
                5930=>'vincentchang@anjukeinc.com',
                5331=>'henrytang@anjukeinc.com'
        );
        if(!empty($sp_user_list[$_SESSION['user_id']])){
            $this->dtp_info = array('name'=>'梁伟平','email'=>'mikeliang@anjukeinc.com','user_id'=>6932);
        }
        $this->mail = Tools_SendMail::get_instance();
        $base_url = "http://".$_SERVER['HTTP_HOST'];
        $this->request->set_attribute('base_url',$base_url);
        //审批人信息
        $this->request->set_attribute('dtp_info',$this->dtp_info);
        $this->post_data = array();
        if(isset($_POST) and count($_POST)>0){
            $this->post_data = $this->request->get_parameters();
            $this->record_trip();
        }
        $this->request->set_attribute('post_data',$this->post_data);
        return 'Oa_Attendance_Trip';
    }

    private function record_trip(){
        $array_emsg = array();//错误信息
        $this->session_act();
        $user_id = $_SESSION['user_id'];
        //上级领导id,下标为领导等级
        $r_user_id = $this->bll->get_sup_id();
        $data = $this->post_data;

        //加入if 如果上传了图片，则做判断 by coldarmy
        $img='';
        /*if($_FILES['file']['tmp_name']) {
            $upDir = 'upload/attendance';
            $uploader = new Tools_Uploader('file');
            $uploader->setValidExt(array(
                '.jpg',
                '.gif'
            ));
            $uploader->setUpDir(CODE_PATH . $upDir); // 需修改为你自己的路径
            if ($uploader->upload()) {
                $img = $uploader->getFileName();
            } else {
                $array_emsg['file_error'] = $uploader->getErrorMsg();
            }
        }*/
        if(!empty($_POST['img_file'])){
            if(strpos($_POST['img_file'],"attendance")){
                $img = str_replace("/upload/attendance/","",$_POST['img_file']);
            }
        }

        //数据组装
        $array_record = array();
        $array_detail = array();
        //写入leave_record表数据
        $array_record['user_id'] = $user_id;
        $array_record['apply_time'] = date("Y-m-d H:i:s",time());
        $array_record['apply_time_ext'] = time();
        $array_record['start_time'] = $data['start_time'];
        $array_record['end_time'] = $data['end_time'];
        $array_record['leave_time'] = $data['leave_time'];
        $array_record['status'] = '未审核';
        $array_record['type'] = "出差";
        $array_record['img'] = $img;
        $array_record['leave_reason'] = $data['leave_reason'];
        $array_record['leave_desc'] = htmlspecialchars($data['note']);
        $array_record['last_touch'] = date("Y-m-d H:i:s");
        $dtp_info = $this->dtp_info;
        //出差直接由部门审批人审批
        $array_record['r_user_id'] = $this->dtp_info['user_id'];

        //数据校验-------------------
        if(empty($array_record['start_time'])){
            $array_emsg['start_time'] = '开始时间必填';
        }
        if(empty($array_record['end_time'])){
            $array_emsg['end_time'] = '结束时间必填';
        }
        $report_bll = new Bll_Attendance_LeaveRecord();
        $chdata=$report_bll->is_ever_apply($data['start_time'],$data['end_time'],'出差',$user_id);
        if($chdata['is_ever']){
            echo "<script type='text/javascript'>alert('当前时间已提交过申')</script>";return;
        }

        //要提前三天申请
        $start_time = $array_record['start_time'];
        $array = explode(" ", $start_time);
        $days = explode("-", $array[0]);
        $time_start = mktime(0,0,0,$days[1],$days[2],$days[0]);
        $dats = getdate(time());
        $time_now = mktime(0,0,0,$dats['mon'],$dats['mday'],$dats['year']);
        if(($time_start-$time_now)<3*86400){
            $array_emsg['time_error'] = "Note:出差必须提前三天申请";
        }
        //时间处理
        if(!(isset($array_msg['start_time']) or isset($array_emsg['end_time']))){
            if($array_record['end_time'] < $array_record['start_time']){
                $array_emsg['time_error'] = "Note:开始时间不能大于结束时间";
            }
        }

        if(!is_numeric(trim($array_record['leave_time']))){
            $array_emsg['leave_time'] = 'Note:出差时间必须为数字';
        }
        $note = trim($array_record['leave_desc']);
        if(empty($note)){
            $array_emsg['note'] = 'Note:注解必填';
        }
        if(empty($data['detail_trip_date'][0]) or empty($data['detail_trip_original'][0]) or empty($data['detail_trip_destingation'][0])){
            $array_emsg['trip_details'] = 'Note:行程除住宿其他必填';
        }
        //-------------------------
        if(count($array_emsg)==0){
            $result = $this->bll->insert_trip_record($array_record);//返回leave_id
            //拆分数据存入库
            $daily_bll = new Bll_Attendance_DailyReport();
            $daily_bll->make_leave_data($result,1);

            //直接写入到audit_list
            //$audit_list = array('uid'=>$array_record['r_user_id'],'leave_id'=>$result,'status'=>1);
            //$this->bll->replace_record($audit_list);
        }
        else{
            $this->request->set_attribute('error_msg',$array_emsg);
            $result = false;
        }
        if($result){
            //TODO 数据校验
            //写入数据成功，获取leave_id
            //写入trip_detail表数据
            $trip_description = $data['leave_reason'];
            $trip_otherinfo = '';
            if($data['leave_reason']=='其他'){
                $trip_otherinfo = trim($data['other_leave_reason']);
            }
            $leave_id = $result;
            foreach($data['detail_trip_date'] as $k=>$v){
                //都为空自动干掉
                if(trim($v)=='' && trim($data['detail_trip_original'][$k])=='' && trim($data['detail_trip_destingation'][$k])=='' && trim($data['detail_trip_hotel'][$k])==''){
                    continue;
                }
                //TODO数据正确性校验
                $array_detail['leave_id'] = $leave_id;
                $array_detail['trip_date'] = $v;
                $array_detail['trip_original'] = $data['detail_trip_original'][$k];
                $array_detail['trip_destingation'] = $data['detail_trip_destingation'][$k];
                $array_detail['trip_method'] = $data['detail_trip_method'][$k];
                $array_detail['trip_start_time'] = $data['detail_trip_start_time'][$k];
                $array_detail['trip_hotel'] = $data['detail_trip_hotel'][$k];
                $array_detail['trip_description'] = $trip_description;
                $array_detail['trip_otherinfo'] = $trip_otherinfo;
                $this->bll->insert_trip_detail($array_detail);
            }
            //邮件通知
            $this->send_notice_email($this->post_data,$leave_id);
            //TODO 都ok了就进行跳转
            echo "<script type='text/javascript'>alert('申请成功')</script>";
        }
        else{
            //若数据不合法，则记录上次数据再进行修改
            $org_info = $this->post_data;
            $this->request->set_attribute('org_info',$org_info);
        }

    }

    private function send_notice_email($data,$leave_id){
        //TODO 对BOSS的特殊处理
        $dpt_info = $this->dtp_info;
        $to = $dpt_info['email'];
        $url = Tools_OAUrls::get_instance()->build_leave_detail_url($leave_id);
        $audit_url = Tools_OAUrls::get_instance()->build_audit_list();
        $title =  "出差申请 - ".$_SESSION['name'];
        $body  = "姓名:".$_SESSION['name']."<br>".
                "城市:".$_SESSION['city_name']."<br>".
                "部门:".$_SESSION['department_name']."<br>".
                "工号:".$_SESSION['code']."<br>".
                "起始时间:".$data['start_time']."<br>".
                "结束时间:".$data['end_time']."<br>".
                "出差时长:".$data['leave_time']."天<br>".
                "出差事由:".$data['leave_reason']."<br>".
                "行程:<br>".$this->_format_trip($data).
                "备注:".$data['leave_desc']."<br>".
                "请点击以下链接审批"."<br><a href ='".$url."'>".$url."</a><br>".
                "如需查看更多,请访问<br><a href ='".$audit_url."'>请点击链接审批</a>(".$audit_url.")";
        $this->mail->send($to, $title, $body);
    }
    private function _format_trip($data){
        $str = '';
        if(empty($data)){
            return $str;
        }
        foreach($data['detail_trip_date'] as $k=> $val){
            $str .= "日期:".$val." 出发地:".$data['detail_trip_original'][$k]." 目的地:".$data['detail_trip_destingation'][$k]." 交通工具:".$data['detail_trip_method'][$k]." 住宿:".$data['detail_trip_hotel'][$k]."晚<br>";
        }
        return $str;
    }
    private function get_bll(){
        apf_require_class('Bll_Attendance_Trip');
        $bll = new Bll_Attendance_Trip();
        $this->bll = $bll;
    }
}
